
<template>
  <RouterView v-slot="{ Component }" v-if="isRouterAlive">
    <KeepAlive>
      <component :is="Component"></component>
    </KeepAlive>
  </RouterView>
</template>

<script setup lang="ts">
import { useBeforeunload } from '@/hooks/useBeforeunload';
import { useUserStore } from '@/stores/user';
import socket from '@/utils/socket';
import { watch, onUnmounted, ref, provide, nextTick } from 'vue';
// import { UseEquipements } from '@/stores/equipements';
import { useMessageStore } from "@/stores/message"
import { UseScreenEqTree } from '@/stores/screen/equipementTree';
import { useAppStore } from '@/stores/modules/app';
import emits from './utils/emits';
import { useIds } from '@/stores/screen/ids';



// const useEquipements = UseEquipements();
const messageStore = useMessageStore()
// const { getDictListAction } = useAppStore()
// const { getEquipementTree } = UseScreenEqTree();
// const { storeGetIDs } = useIds()
// 浏览器刷新时关闭websocket
useBeforeunload(socket.close);
const uerStore = useUserStore()
watch(
  () => uerStore.token,
  token => {
    if (token) {
      // useEquipements.getIds('yunyang');
      // getEquipementTree();
      // getDictListAction();
      // storeGetIDs();
      socket.init((data: any) => {
        if (data && JSON.parse(data)) {
          data = JSON.parse(data)
          if (data) {
            const { businessType, content } = data
            switch (businessType) {
              case 'ALERT_MESSAGE': // 设备告警触发时的通知
                // 下发设备告警消息通知
                emits.emit(businessType, content)
                // 添加未读消息列表
                messageStore.addMessageAction(content)
                // 添加广播队列，并按顺序播放
                // if (content.alertToneUrl) {
                //   audioPlayer.addAudio(content.alertToneUrl)
                //   audioPlayer.play()
                // }
                break
              case 'HANDLE_MESSAGE': // 设备告警变已处理时的通知
                // 下发设备告警消息更新

                emits.emit(businessType, content)
                break
              // case 'READ_MESSAGE': // 未读消息变为已读时的通知
              //   // 从未读消息列表移除最新已读消息
              //   messageStore.removeMessageAction(content.id)
              //   break
              default:

            }
          }
        }
      })

    } else {
      socket.close()
    }
  },
  {
    immediate: true
  }
)
const isRouterAlive = ref(true)

// 全局注入刷新页面的方法
provide('reload', () => {
  isRouterAlive.value = false
  nextTick(() => {
    isRouterAlive.value = true
  })
})



onUnmounted(() => {
  socket.close()
  emits.all.clear()

})
</script>

<style lang="scss" scoped></style>
